import axios from 'axios';
import Router from '@/router';
import elementUI, {Message} from 'element-ui';

import Vue from "vue";

Vue.prototype.$router = Router;
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(elementUI);
const instance = axios.create({
    baseURL: '/api',
});

instance.interceptors.request.use(config => {
    const token = sessionStorage.getItem('token');
    if (token) {
        config.headers.token = token;
    }
    return config;
}, error => {
    return Promise.reject(error);
});
//前端拦截器
//TODO  import引入的时候一定注意不要引错成默认axios，并且在写请求方法的时候一定要写.catch(() => {}) 否则无法处理200以外的状态码
instance.interceptors.response.use(response => {
    if(response.data === null || response.data === undefined || response.data === ''){
        Message.error('请求异常，请联系管理员');
    } else if (response.data.code === 200) {
        return response.data;
    } else if (response.data.code === 401) {
        Message.error('身份已过期，请重新登录');
        setTimeout(() => {
            window.location.href = '/login';
        }, 1500);
    } else if (response.data.code === 403) {
        Message.error('权限不足');
    } else if (response.data.code === 404) {
        Message.error('请求地址不存在');
        setTimeout(() => {
            window.location.href = '/login';
        }, 1500);
    } else if (response.data.code === 500) {
        if (response.data.msg && response.data.msg !== '') {
            Message.error(response.data.msg);
        } else {
            Message.error('网络异常');
        }
    }
    return Promise.reject(response);
}, error => {
    return Promise.reject(error);
});
export default instance;
